package com.freight.user.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.core.service.UserService;
import com.freight.user.dao.*;
import com.freight.user.dto.DriverInfoDto;
import com.freight.user.entity.*;
import com.freight.user.mapper.CompanyVoMapper;
import com.freight.user.mapper.DriverVoMapper;
import com.freight.user.service.*;
import com.freight.user.util.UserDtoUtils;
import com.freight.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 司机用户信息表接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class DriverUserServiceImpl implements DriverUserService {

    @Autowired
    private DriverUserDao driverUserDao;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private DriverUserService driverUserService;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    IdCardService idCardService;

    @Autowired
    DriverLicenseService driverLicenseService;

    @Autowired
    VehicleLicenseService vehicleLicenseService;

    @Autowired
    UserService userService;

    @Autowired
    private CompanyVoMapper companyVoMapper;

    @Autowired
    private DriverLicenseDao driverLicenseDao;

    @Autowired
    private IdCardDao idCardDao;

    @Override
    public DriverUserDao getRepository() {
        return driverUserDao;
    }

    @Override
    public DriverUser saveDriverUser(DriverInfoDto driverInfoDto) {

        User u = securityUtil.getCurrUser();
        Long userId = driverInfoDto.getUserId();

        String logContent = "";

        List<DriverCompanyVo> dr=companyVoMapper.getCompanyByUserCard(driverInfoDto.getNum());
        if(dr!=null&&dr.size()>1){
            throw new FreightException("身份证已绑定其他用户");
        }
        if(dr!=null&&dr.size()>0&&!dr.get(0).getUserId().equals(userId)){
            throw new FreightException("身份证已绑定其他用户");
        }

        DriverUser du = driverUserService.findByUserId(userId);
        if (du == null) {
            du = new DriverUser();
            du.setUserId(userId);
        }

        Long idCardId =  du.getIdCardId();
        // 上传过身份证
        IdCard idDetail = null;
        if (idCardId != null && idCardId > 0) {
            idDetail = idCardDao.getOne(idCardId);

            if(du.getDriverUserStatus()==3&&!idDetail.getNum().equals(driverInfoDto.getNum())){
                throw new FreightException("不能更换身份证");
            }
            ObjectUtil.copyPropertiesIgnoreNull(driverInfoDto, idDetail);
            logContent = "修改驾驶员信息";
        } else {
            idDetail = new IdCard();
            ObjectUtil.copyPropertiesIgnoreNull(driverInfoDto, idDetail);
            logContent = "上传驾驶员信息";
        }
        idDetail = idCardDao.save(idDetail);

        du.setIdCardId(idDetail.getId());


        // 上传过
        Long driverId = du.getDriverId();

        DriverLicense driverLicense = null;
        if (driverId != null && driverId > 0) {
            driverLicense = driverLicenseDao.getOne(driverId);
            ObjectUtil.copyPropertiesIgnoreNull(driverInfoDto, driverLicense);
        } else {
            driverLicense = new DriverLicense();
            ObjectUtil.copyPropertiesIgnoreNull(driverInfoDto, driverLicense);
        }
        driverLicense = driverLicenseDao.save(driverLicense);
        du.setDriverId(driverLicense.getId());

        if(u.getUserType() == 2 && du.getDriverUserStatus() == 1){
            du.setDriverUserStatus(CommonConstant.REGISTED);
        }else {
            du.setDriverUserStatus(CommonConstant.REGISTING);
        }

        du = driverUserDao.save(du);

        //操作记录
        operationLogService.saveOperationLog(2,logContent,userId.toString());

        return du;
    }

    @Override
    public void saveDriverInfo(DriverInfoDto driverInfoDto) {

        User user=userService.get(driverInfoDto.getUserId());

        DriverUser du = saveDriverUser(driverInfoDto);

        user.setNickName(driverInfoDto.getName());
        userService.save(user);
    }






    @Override
    public Page<DriverUser> findByCondition(DriverUser driverUser, SearchVo searchVo, Pageable pageable) {

        return driverUserDao.findAll(new Specification<DriverUser>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<DriverUser> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");

                List<Predicate> list = new ArrayList<>();

                // 创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

    @Override
    public DriverUser findByUserId(Long userId) {
        return driverUserDao.findByUserId(userId);
    }

    @Override
    public DriverUser findByVehicleId(Long vehicleId) {
        return driverUserDao.findByVehicleId(vehicleId);
    }




    @Override
    public DriverAllPicId getDriverPicId(Long userId) {
        User u = securityUtil.getCurrUser();
        userId = UserDtoUtils.getCurrentUserId(u, userId);

        DriverUser du = driverUserDao.findByUserId(userId);

        Long idCardId = du.getIdCardId();
        Long lId = du.getVehicleId();


        IdCard idCard = idCardService.get(idCardId);

        VehicleLicense vehicleLicense = vehicleLicenseService.get(lId);

        DriverAllPicId companyAllPicId = new DriverAllPicId();

        if (idCard != null) {
            companyAllPicId.setIdCardBackPicFileId(idCard.getIdCardBackPicFileId());
            companyAllPicId.setIdCardFontPicFileId(idCard.getIdCardFontPicFileId());
        }



        if (vehicleLicense != null) {
            ObjectUtil.copyPropertiesIgnoreNull(vehicleLicense, companyAllPicId);
        }
        return companyAllPicId;
    }
}